package com.ncucoder.soms.controller;

import com.ncucoder.soms.dto.LoginUserDTO;
import com.ncucoder.soms.dto.ResponseDTO;
import com.ncucoder.soms.service.UserService;
import com.ncucoder.soms.util.JwtTokenUtils;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author <a href="https://www.ncucoder.com">hsowan</a>
 * @date 2019-07-19
 **/
@RestController
public class AuthController {

    private final UserService userService;

    public AuthController(UserService userService) {
        this.userService = userService;
    }

    @ApiOperation("获取token")
    @PostMapping("/auth/token")
    public ResponseDTO getJwtToken(@RequestBody LoginUserDTO loginUserDTO) {
        String username = loginUserDTO.getUsername();
        String password = loginUserDTO.getPassword();

        if (username == null || "".equals(username)) {
            return new ResponseDTO(ResponseDTO.BAD_REQUEST, "用户名不能为空");
        }

        if (password == null || "".equals(password)) {
            return new ResponseDTO(ResponseDTO.BAD_REQUEST, "密码不能为空");
        }

        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);
            String role = userService.getRoleByUsername(username);
            String jwtToken = JwtTokenUtils.TOKEN_PREFIX + JwtTokenUtils.createToken(username, role);
            return new ResponseDTO(ResponseDTO.OK, jwtToken);
        } catch (AuthenticationException e) {
            // 登录失败
            return new ResponseDTO(ResponseDTO.UNAUTHORIZED, e.getMessage());
        }
    }
}
